const query = require('./fun')
const sqlCount = 'SQL_CALC_FOUND_ROWS';
const { USER, MOVIE, COMMENT, PERFORMER, RELATION, PRAISE, FOLLOW, COMM, HOT,NEWS,MEDIA,COLLECTION } = require('./database')
let { sqlUpdateStr, sqlAddStr, sqlSelectStr, sqlWhereStr } = require('../util.js');
/**
 * 判断是否存在用户
 */
function isUser(data) {
    return new Promise((resolve, reject) => {
        query(`select  * from ${USER} where openid=?`, data)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(reject)
            })
    })
}
/**
 * 添加用户
 */
function addUser(data) {
    return new Promise((resolve, reject) => {
        query(`INSERT INTO ${USER} (userId,openid,session_key) VALUES(null,?,?) `, data)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(reject)
            })
    })
}
/**
 * 修改用户信息
 */
function updataUser(userId, data) {
    return new Promise((resolve, reject) => {
        let sql = '';
        Object.entries(data).forEach(item => {
            if (sql.toString()) {
                sql += ',';
            }
            sql += `${item[0]}="${item[1]}"`
        })
        query(`UPDATE ${USER} SET ${sql} WHERE userId=${userId}`)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(reject)
            })
    })
}
/**
 * 根据用户的id返回用户信息
 */
function GetUsersById(id) {
    return new Promise((resolve, reject) => {
        query(`select userName,userUrl,usercontent,userCountry,userSex,userId from ${USER} where userId=?`, { id })
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(reject)
            })
    })
}
/**
 * 获取电影分类信息
 */
function getMovietype() {
    return new Promise((resolve, reject) => {
        query([`select *  from ${MOVIE} where movieType='热播'`, `select * from ${MOVIE}  where movieType='即将上映'`, `SELECT * FROM ${MOVIE} where movieType='热播' ORDER BY CAST(movieScore AS SIGNED) desc  limit 6`])
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(reject)
            })
    })
}
/**
 * 获取不同分类电影的数目
 */
function getMovieTypeCount(like) {
    return new Promise((resolve, reject) => {
        let condition = '';
        condition = sqlSelectStr(condition, like);
        query(`select   count(*) as counts from ${MOVIE} ${condition}`)
            .then((res) => {
                resolve(res[0]['counts'])
            })
            .catch((err) => {
                reject(err)
            })
    });
}
/**
 * 获取电影信息列表
 */
function getMovieListUser(num, limit, like) {
    return new Promise((resolve, reject) => {
        let condition = '';
        condition = sqlSelectStr(condition, like);
        query(`select  ${sqlCount} * from ${MOVIE} ${condition}  limit ?,${limit}`, { num }, true)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 获取指定id的电影信息
 */
function getMovieById(movieId) {
    return new Promise((resolve, reject) => {
        query(`select * from ${MOVIE} where movieId=?`, { movieId })
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 获取电影的评论
 */
function getCommentAll(movieId) {
    return new Promise((resolve, reject) => {
        let condition = '';
        condition += ` where `
        condition += `${USER}.userId=${COMMENT}.userId and ${MOVIE}.movieId=${COMMENT}.movieId and ${COMMENT}.movieId=${movieId}`
        query(`select  ${sqlCount} ${COMMENT}.*,${USER}.userName,${MOVIE}.movieName,${USER}.userUrl from ${COMMENT},${USER},${MOVIE} ${condition} `)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 获取热门评论
 */
function getHotCommentById(movieId) {
    return new Promise((resolve, reject) => {
        let condition = '';
        condition += ` where `
        condition += `${USER}.userId=${COMMENT}.userId and ${MOVIE}.movieId=${COMMENT}.movieId and ${COMMENT}.movieId=${movieId} ORDER BY CAST(commentPraise AS SIGNED) desc  limit 6`
        query(`select  ${sqlCount} ${COMMENT}.*,${USER}.userName,${MOVIE}.movieName,${USER}.userUrl from ${COMMENT},${USER},${MOVIE} ${condition} `)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 *获取最新的评论 
 */
function getNewCommentById(num, limit, movieId) {
    return new Promise((resolve, reject) => {
        let condition = '';
        condition += ` where `
        condition += `${USER}.userId=${COMMENT}.userId and ${MOVIE}.movieId=${COMMENT}.movieId and ${COMMENT}.movieId=${movieId} and TIMESTAMPDIFF(SECOND,${COMMENT}.commentTime,now())>0 order by ${COMMENT}.commentTime  desc  limit ${num},${limit}`
        query(`select  ${sqlCount} ${COMMENT}.*,${USER}.userName,${MOVIE}.movieName,${USER}.userUrl from ${COMMENT},${USER},${MOVIE} ${condition} `)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 获取指定电影的所有评论
 */
function getCommentBymovieId(movieId) {
    return new Promise((resolve, reject) => {
        let condition = '';
        condition += ` where `
        condition += `${USER}.userId=${COMMENT}.userId and ${MOVIE}.movieId=${COMMENT}.movieId and ${COMMENT}.movieId=${movieId}`
        query(`select  ${sqlCount} ${COMMENT}.*,${USER}.userName,${MOVIE}.movieName,${USER}.userUrl from ${COMMENT},${USER},${MOVIE} ${condition}`)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 修改电影的评分
 */
function upDataCommentScore(data, movieId) {
    return new Promise((resolve, reject) => {
        let sql = '';
        sql = sqlUpdateStr(sql, data);
        query(`UPDATE ${MOVIE} SET ${sql} WHERE movieId=${movieId}`)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 获取关注的评论
 */
function getFollowCommmentById(num, limit, movieId, userId) {
    return new Promise((resolve, reject) => {
        let condition = '';
        condition += ` where `
        condition += `${USER}.userId=${COMMENT}.userId and ${MOVIE}.movieId=${COMMENT}.movieId and ${COMMENT}.movieId=${movieId} and ${FOLLOW}.touserId=${USER}.userId and ${FOLLOW}.userId=${userId} limit ${num},${limit}`
        query(`select  ${sqlCount} ${COMMENT}.*,${USER}.userName,${MOVIE}.movieName,${USER}.userUrl from ${COMMENT},${USER},${MOVIE},${FOLLOW} ${condition} `)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 获取自己的评论
 */
function getUserCommentById(movieId, userId) {
    return new Promise((resolve, reject) => {
        let condition = '';
        condition += ` where `
        condition += `${USER}.userId=${COMMENT}.userId and ${MOVIE}.movieId=${COMMENT}.movieId and ${COMMENT}.movieId=${movieId} and ${USER}.userId=${userId}`
        query(`select  ${sqlCount} ${COMMENT}.*,${USER}.userName,${MOVIE}.movieName,${USER}.userUrl from ${COMMENT},${USER},${MOVIE} ${condition} `)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 添加评论
 */
function addComment(data) {
    return new Promise((resolve, reject) => {
        let obj = sqlAddStr(data);
        query(`INSERT INTO ${COMMENT}(${obj.keys}) VALUES(${obj.vals}) `)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 查看影人
 */
function getPerformerById(id) {
    return new Promise((resolve, reject) => {
        query(`select * from ${PERFORMER} where performerId=?`, { id })
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 关系表
 */
function addRelation(data) {
    return new Promise((resolve, reject) => {
        let obj = sqlAddStr(data);
        query(`INSERT INTO ${RELATION}(${obj.keys}) VALUES(${obj.vals}) `)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 判断是否已经存在关系
 */
function isaddRelation(data) {
    return new Promise((resolve, reject) => {
        let sql = '';
        sql = sqlWhereStr(sql, data)
        query(`select * from ${RELATION} ${sql}`)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 修改关系
 */
function updataRelation(relationId, data) {
    return new Promise((resolve, reject) => {
        let sql = '';
        sql = sqlUpdateStr(sql, data);
        query(`UPDATE ${RELATION} SET ${sql} WHERE relationId=${relationId}`)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 判断是否点赞
 */
function isaddPraise(data) {
    return new Promise((resolve, reject) => {
        let sql = '';
        sql = sqlWhereStr(sql, data)
        query(`select * from ${PRAISE} ${sql}`)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 取消点赞
 */
function delPraise(praiseId) {
    return new Promise((resolve, reject) => {
        query(`DELETE FROM ${PRAISE} WHERE praiseId=?`, { praiseId })
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 点赞
 */
function addPraise(data) {
    return new Promise((resolve, reject) => {
        let obj = sqlAddStr(data);
        query(`INSERT INTO ${PRAISE}(${obj.keys}) VALUES(${obj.vals}) `)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 评论点赞数目改变
 */
function changecommentPraise(data) {
    return new Promise((resolve, reject) => {
        let sql = `commentPraise=commentPraise+${data.PraiseNum}`;
        query(`UPDATE ${COMMENT} SET ${sql} WHERE commentId=${data.commentId}`)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(reject)
            })
    })
}
/**
 * 判断是否关注
 */
function isaaddFollow(data) {
    return new Promise((resolve, reject) => {
        let sql = '';
        sql = sqlWhereStr(sql, data)
        query(`select * from ${FOLLOW} ${sql}`)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 取消关注
 */
function delFollow(followId) {
    return new Promise((resolve, reject) => {
        query(`DELETE FROM ${FOLLOW} WHERE followId=?`, { followId })
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 关注
 */
function addFollow(data) {
    return new Promise((resolve, reject) => {
        let obj = sqlAddStr(data);
        query(`INSERT INTO ${FOLLOW}(${obj.keys}) VALUES(${obj.vals}) `)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 根据id查看信息
 */
function getCommentById(commentId) {
    return new Promise((resolve, reject) => {
        query(`select ${COMMENT}.*,${USER}.userName,${MOVIE}.movieName,${USER}.userUrl from ${COMMENT},${USER},${MOVIE} where commentId=? and ${COMMENT}.userId=${USER}.userId and ${MOVIE}.movieId=${COMMENT}.movieId`, { commentId })
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    });
}
/**
 * 获取二级评论
 */
function getCommList(num, limit, commentId) {
    return new Promise((resolve, reject) => {
        let condition = '';
        condition += ` where `
        condition += `${USER}.userId=${COMM}.userId and ${COMM}.commentId=${commentId} and ${USER}.userId=${COMM}.userId limit ${num},${limit}`
        query(`select  ${sqlCount} ${USER}.userName,${USER}.userUrl,${COMM}.* from ${COMM},${USER} ${condition} `)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 添加二级评论
 */
function addComm(data) {
    return new Promise((resolve, reject) => {
        let obj = sqlAddStr(data);
        query(`INSERT INTO ${COMM}(${obj.keys}) VALUES(${obj.vals}) `)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 获取用户想看的电影
 */
function getSeenMovie(userId) {
    return new Promise((resolve, reject) => {
        query(`select ${MOVIE}.*,${RELATION}.relationType,${RELATION}.relationTime from ${MOVIE},${RELATION} where ${RELATION}.userId=? and ${MOVIE}.movieId=${RELATION}.movieId and ${RELATION}.relationType='看过'`, { userId })
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 获取用户看过的电影
 */
function getWantMovie(userId) {
    return new Promise((resolve, reject) => {
        query(`select ${MOVIE}.*,${RELATION}.relationType,${RELATION}.relationTime from ${MOVIE},${RELATION} where ${RELATION}.userId=? and ${MOVIE}.movieId=${RELATION}.movieId and ${RELATION}.relationType='想看'`, { userId })
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 获取热搜
 */
function getHotList() {
    return new Promise((resolve, reject) => {
        query(`select * from ${HOT} order by hotId desc limit 0,10`)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 获取新闻列表
 */
function getNewsList(num, limit, like = {}) {
    return new Promise((resolve, reject) => {
        let condition = '';
        condition = sqlSelectStr(condition, like);
        if (!String(condition).length) {
            condition += ` where `
        } else {
            condition += ` and `
        }
        condition += `${NEWS}.mediaId=${MEDIA}.mediaId`
        query(`select  ${sqlCount} ${NEWS}.*,${MEDIA}.* from ${NEWS},${MEDIA} ${condition}  limit ?,${limit}`, { num }, true)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 获取新闻详情
 */
function GetnewsById(newsId) {
    return new Promise((resolve, reject) => {
        query(`select ${NEWS}.*,${MEDIA}.* from ${NEWS},${MEDIA} where newsId=? and ${NEWS}.mediaId=${MEDIA}.mediaId`, { newsId })
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 判断是否收藏
 */
function isCollection(data) {
    return new Promise((resolve, reject) => {
        let sql = '';
        sql = sqlWhereStr(sql, data)
        query(`select * from ${COLLECTION} ${sql}`)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 取消收藏
 */
function delCollection(collectionId) {
    return new Promise((resolve, reject) => {
        query(`DELETE FROM ${COLLECTION} WHERE collectionId=?`, { collectionId })
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 收藏
 */
function addCollection(data) {
    return new Promise((resolve, reject) => {
        let obj = sqlAddStr(data);
        query(`INSERT INTO ${COLLECTION}(${obj.keys}) VALUES(${obj.vals}) `)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
/**
 * 新闻阅读数目改变
 */
function changeNewsReading(data) {
    console.log(data)
    return new Promise((resolve, reject) => {
        let sql = `newsReading=newsReading+${data.newsReading}`;
        query(`UPDATE ${NEWS} SET ${sql} WHERE newsId=${data.newsId}`)
            .then((res) => {
                resolve(res)
            })
            .catch((err) => {
                reject(reject)
            })
    })
}
exports.isUser = isUser;
exports.addUser = addUser;
exports.updataUser = updataUser;
exports.GetUsersById = GetUsersById;
exports.getMovietype = getMovietype;
exports.getMovieTypeCount = getMovieTypeCount;
exports.getMovieListUser = getMovieListUser;
exports.getMovieById = getMovieById;
exports.getCommentAll = getCommentAll;
exports.getHotCommentById = getHotCommentById;
exports.getNewCommentById = getNewCommentById;
exports.addComment = addComment;
exports.getPerformerById = getPerformerById;
exports.addRelation = addRelation;
exports.isaddRelation = isaddRelation;
exports.updataRelation = updataRelation;
exports.isaddPraise = isaddPraise;
exports.delPraise = delPraise;
exports.addPraise = addPraise;
exports.changecommentPraise = changecommentPraise;
exports.isaaddFollow = isaaddFollow;
exports.delFollow = delFollow;
exports.addFollow = addFollow;
exports.getFollowCommmentById = getFollowCommmentById;
exports.getCommentById = getCommentById;
exports.getCommList = getCommList;
exports.addComm = addComm;
exports.getSeenMovie = getSeenMovie;
exports.getWantMovie = getWantMovie;
exports.getHotList = getHotList;
exports.getUserCommentById = getUserCommentById;
exports.getCommentBymovieId = getCommentBymovieId;
exports.upDataCommentScore=upDataCommentScore;
exports.getNewsList=getNewsList;
exports.GetnewsById=GetnewsById;
exports.isCollection=isCollection;
exports.delCollection=delCollection;
exports.addCollection=addCollection;
exports.changeNewsReading=changeNewsReading;